<template>
  <div class="page-content">
    <div class="header">
      <h3>租用列表</h3>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="设备昵称/设备标识" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="rent-table">
      <el-table
        v-loading="loading"
        :data="rentList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="nick_name" label="设备昵称" width="120" />
        <el-table-column prop="phone_identify" label="设备标识" width="160" />
        <el-table-column prop="consul_id" label="服务器" width="120" />
        <el-table-column prop="android_version" label="安卓版本" width="100">
          <template #default="scope">{{ scope.row.android_version || '-' }}</template>
        </el-table-column>
        <el-table-column prop="vip_level" label="套餐等级" width="100">
          <template #default="scope">
            <el-tag :type="getVipTagType(scope.row.vip_level)">
              {{ scope.row.vip_level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160" />
        <el-table-column prop="over_time" label="到期时间" width="160">
          <template #default="scope">
            <span :class="isExpired(scope.row.over_time) ? 'expired' : 'active'">
              {{ scope.row.over_time }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="isExpired(scope.row.over_time) ? 'danger' : 'success'">
              {{ isExpired(scope.row.over_time) ? '已过期' : '租用中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="剩余时间" width="120">
          <template #default="scope">
            {{ getRemainingTime(scope.row.over_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" plain @click="showRentDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="租用详情" width="60%">
      <el-descriptions bordered :column="2">
        <el-descriptions-item label="租用ID">{{ currentDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.user_id }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ currentDetail.phone_id }}</el-descriptions-item>
        <el-descriptions-item label="设备昵称">{{ currentDetail.nick_name }}</el-descriptions-item>
        <el-descriptions-item label="设备标识">{{ currentDetail.phone_identify }}</el-descriptions-item>
        <el-descriptions-item label="服务器">{{ currentDetail.consul_id }}</el-descriptions-item>
        <el-descriptions-item label="安卓版本">{{ currentDetail.android_version || '-' }}</el-descriptions-item>
        <el-descriptions-item label="套餐等级">{{ currentDetail.vip_level }}</el-descriptions-item>
        <el-descriptions-item label="套餐ID">{{ currentDetail.vip_id }}</el-descriptions-item>
        <el-descriptions-item label="ADB类型">{{ currentDetail.adb_type ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentDetail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentDetail.updated_at }}</el-descriptions-item>
        <el-descriptions-item label="到期时间" :span="2">
          <span :class="isExpired(currentDetail.over_time) ? 'expired' : 'active'">
            {{ currentDetail.over_time }}
            <el-tag :type="isExpired(currentDetail.over_time) ? 'danger' : 'success'" size="small" style="margin-left: 8px;">
              {{ isExpired(currentDetail.over_time) ? '已过期' : '租用中' }}
            </el-tag>
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRentList, type RentData, type RentQueryParams } from '@/Newapi/rent'

// 搜索表单
const searchForm = reactive({
  keyword: '',
})

// 表格数据
const rentList = ref<RentData[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<RentData>({} as RentData)

// 加载租用列表
const loadRentList = async () => {
  loading.value = true
  try {
    const params: RentQueryParams = {
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: 'over_time'
    }
    
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    
    const res = await getRentList(params)
    if (res.code === 200) {
      rentList.value = res.data
      total.value = res.data.length // 由于返回的数据没有total字段，使用数组长度作为替代
    } else {
      ElMessage.error(res.msg || '获取租用列表失败')
    }
  } catch (error) {
    console.error('获取租用列表出错:', error)
    ElMessage.error('获取租用列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  currentPage.value = 1
  loadRentList()
}

// 重置查询
const resetSearch = () => {
  searchForm.keyword = ''
  currentPage.value = 1
  loadRentList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadRentList()
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadRentList()
}

// 显示租用详情
const showRentDetail = (row: RentData) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 检查是否已过期
const isExpired = (overTime: string): boolean => {
  if (!overTime) return true
  const overDate = new Date(overTime)
  const now = new Date()
  return overDate < now
}

// 获取剩余时间
const getRemainingTime = (overTime: string): string => {
  if (!overTime) return '已过期'
  
  const overDate = new Date(overTime)
  const now = new Date()
  
  if (overDate < now) {
    return '已过期'
  }
  
  const diffMs = overDate.getTime() - now.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  
  if (diffDays > 0) {
    return `${diffDays}天${diffHours}小时`
  } else if (diffHours > 0) {
    return `${diffHours}小时`
  } else {
    const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
    return `${diffMinutes}分钟`
  }
}

// 获取套餐标签类型
const getVipTagType = (vipLevel: string): string => {
  if (!vipLevel) return ''
  
  const vipLevelLower = vipLevel.toLowerCase()
  if (vipLevelLower.includes('g')) {
    return 'success'
  } else if (vipLevelLower.includes('vip')) {
    return 'primary'
  } else {
    return 'info'
  }
}

// 页面挂载时加载数据
onMounted(() => {
  loadRentList()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .search-bar {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  
  .rent-table {
    .expired {
      color: #f56c6c;
    }
    
    .active {
      color: #67c23a;
    }
    
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 